#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QRegularExpression>
#include <QDateTime>
#include <QMessageBox>
#include <QJsonDocument>
#include <QJsonObject>
#include <QValueAxis>
#include <csignal>  // 添加这个头文件
#include <QNetworkInterface>  // 网络接口相关
#include <QHostAddress>       // IP地址处理
#include <QDebug>

void MainWindow::setupPowerControlUI()
{
    // 创建电源控制工具按钮
    powerToolButton = new QToolButton(this);
    powerToolButton->setText(tr("Power Control"));
    powerToolButton->setPopupMode(QToolButton::InstantPopup);
    powerToolButton->setToolButtonStyle(Qt::ToolButtonTextOnly);
    powerToolButton->setStyleSheet("QToolButton { padding: 5px; }");

    // 创建主菜单
    powerMenu = new QMenu(this);
    powerMenu->setStyleSheet(
        "QMenu { background-color: #f0f0f0; border: 1px solid #ccc; }"
        "QMenu::item { padding: 5px 20px 5px 10px; }"
        "QMenu::item:selected { background-color: #d0d0d0; }"
        );

    // 1. 相机电源子菜单
    QMenu* cameraMenu = createPowerSubMenu("Camera Power", ":/icons/camera.png");

    // 2. 加热电源子菜单
    QMenu* heatMenu = createPowerSubMenu("Heat Power", ":/icons/heat.png");

    // 3. 真空电源子菜单
    QMenu* vaccuMenu = createPowerSubMenu("Vaccu Power", ":/icons/vacuum.png");

    // 修改连接方式，不再依赖旧状态
    connect(cameraMenu, &QMenu::aboutToShow, [this]() {
        // 初始状态设为未知（由心跳包更新）
        updatePowerButtonStates(btnCameraPowerOn, btnCameraPowerOff, m_currentIOStatus.cameraPower);
    });

    connect(heatMenu, &QMenu::aboutToShow, [this]() {
        updatePowerButtonStates(btnHeatPowerOn, btnHeatPowerOff, m_currentIOStatus.heatingPower);
    });

    connect(vaccuMenu, &QMenu::aboutToShow, [this]() {
        updatePowerButtonStates(btnVaccuPowerOn, btnVaccuPowerOff, m_currentIOStatus.vacuumPower);
    });

    // 添加到主菜单
    powerMenu->addMenu(cameraMenu);
    powerMenu->addMenu(heatMenu);
    powerMenu->addMenu(vaccuMenu);

    // 设置工具按钮的菜单
    powerToolButton->setMenu(powerMenu);

    // 添加到工具栏
    ui->mainToolBar->addWidget(powerToolButton);
}


QMenu* MainWindow::createPowerSubMenu(const QString& title, const QString& iconPath)
{
    QMenu* subMenu = new QMenu(title, this);

    // 设置子菜单样式
    subMenu->setStyleSheet(
        "QMenu { background-color: #f8f8f8; border: 1px solid #ddd; }"
        "QMenu::item { padding: 5px 15px; }"
        "QMenu::item:selected { background-color: #e0e0e0; }"
        );

    // 添加图标
    if (QFile::exists(iconPath)) {
        subMenu->setIcon(QIcon(iconPath));
    }

    // 创建按钮容器
    QWidget* buttonWidget = new QWidget();
    QHBoxLayout* buttonLayout = new QHBoxLayout(buttonWidget);
    buttonLayout->setContentsMargins(5, 2, 5, 2);
    buttonLayout->setSpacing(5);

    // 创建On/Off按钮
    QPushButton* onButton = new QPushButton("On", buttonWidget);
    QPushButton* offButton = new QPushButton("Off", buttonWidget);

    // 设置按钮样式
    QString buttonStyle =
        "QPushButton {"
        "   padding: 3px 8px;"
        "   border: 1px solid #aaa;"
        "   border-radius: 3px;"
        "}"
        "QPushButton:hover {"
        "   background-color: #e0e0e0;"
        "}"
        "QPushButton:checked {"
        "   background-color: #4CAF50;"
        "   color: white;"
        "}"
        "QPushButton:checked:hover {"
        "   background-color: #45a049;"
        "}";

    onButton->setStyleSheet(buttonStyle);
    offButton->setStyleSheet(buttonStyle);

    // 添加到布局
    buttonLayout->addWidget(onButton);
    buttonLayout->addWidget(offButton);

    // 创建WidgetAction
    QWidgetAction* buttonAction = new QWidgetAction(subMenu);
    buttonAction->setDefaultWidget(buttonWidget);

    // 添加到子菜单
    subMenu->addAction(buttonAction);
    // 添加悬停效果
    subMenu->setAttribute(Qt::WA_TranslucentBackground);
    subMenu->setWindowFlags(subMenu->windowFlags() | Qt::FramelessWindowHint);
    subMenu->setAttribute(Qt::WA_TranslucentBackground);

    // 添加动画效果
    QGraphicsOpacityEffect* opacityEffect = new QGraphicsOpacityEffect(subMenu);
    subMenu->setGraphicsEffect(opacityEffect);
    QPropertyAnimation* animation = new QPropertyAnimation(opacityEffect, "opacity");
    animation->setDuration(150);
    animation->setStartValue(0);
    animation->setEndValue(1);
    animation->start();

    // 返回按钮指针
    if (title.contains("Camera")) {
        btnCameraPowerOn = onButton;
        btnCameraPowerOff = offButton;
    }
    else if (title.contains("Heat")) {
        btnHeatPowerOn = onButton;
        btnHeatPowerOff = offButton;
    }
    else if (title.contains("Vaccu")) {
        btnVaccuPowerOn = onButton;
        btnVaccuPowerOff = offButton;
    }

    return subMenu;
}

void MainWindow::updatePowerButtonStates(QPushButton* onBtn, QPushButton* offBtn, bool isOn) {
    // 确保在主线程执行UI操作
    if (QThread::currentThread() != this->thread()) {
        QMetaObject::invokeMethod(this, "updatePowerButtonStates",
                                  Qt::QueuedConnection,
                                  Q_ARG(QPushButton*, onBtn),
                                  Q_ARG(QPushButton*, offBtn),
                                  Q_ARG(bool, isOn));
        return;
    }

    // 更新按钮状态
    onBtn->setChecked(isOn);
    offBtn->setChecked(!isOn);

    // 动态样式表
    QString activeStyle = "background-color: %1; color: white; border: 1px solid %2;";

    onBtn->setStyleSheet(isOn ?
                             activeStyle.arg("#4CAF50").arg("#45a049") :
                             "background-color: none; color: black;");

    offBtn->setStyleSheet(!isOn ?
                              activeStyle.arg("#f44336").arg("#d32f2f") :
                              "background-color: none; color: black;");

    // 更新工具提示
    onBtn->setToolTip(isOn ? "设备已通电" : "点击通电");
    offBtn->setToolTip(!isOn ? "设备已断电" : "点击断电");
}

void MainWindow::check4720PowerStatus() {
//    QFile file("/home/csst/PS_mosaic/camera.status");
    QFile file("/home/meph/PS_mosaic/camera.status");
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        LOG_CAMERA("无法打开状态文件:");
        return;
    }

    bool isPowered = false;
    while (!file.atEnd()) {
        QString line = file.readLine().trimmed();
        if (line.startsWith("power_status_4720=")) {
            isPowered = (line.split("=")[1] == "1");
            break;
        }
    }
    file.close();

    // 更新指示灯
    QString color = isPowered ? "green" : "red";
    QString tooltip = isPowered ? "4720相机已上电" : "4720相机未上电";

    ui->labelPower4720->setStyleSheet(
        QString("border-radius: 8px; background-color: %1;").arg(color)
        );
    ui->labelPower4720->setToolTip(tooltip);

    // 可选：记录状态变化
    static bool lastStatus = false;
    if(lastStatus != isPowered) {
        qDebug() << QDateTime::currentDateTime().toString()
        << "4720电源状态变化:" << (isPowered ? "ON" : "OFF");
        lastStatus = isPowered;
    }

     ui->btnSetReadoutRate_2->setEnabled(isPowered);
}
